import os
import sqlite3

import bs4
from anyio.lowlevel import checkpoint
from dotenv import load_dotenv
from langgraph.prebuilt import create_react_agent
from langchain.chat_models import init_chat_model
from langchain_chroma import Chroma
from langchain_community.document_loaders import WebBaseLoader
from langchain_ollama import ChatOllama, OllamaEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langgraph.graph import MessagesState, StateGraph
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage
from langgraph.graph import END
from langgraph.prebuilt import ToolNode, tools_condition
from PIL import Image
from langgraph.checkpoint.memory import MemorySaver
from langgraph.checkpoint.sqlite import SqliteSaver

load_dotenv(".venv/.env")

def init_vector_store():
    db_path = "./chroma_langchain_db"
    # 建议使用ollama3.2，因为它更小一点
    embeddings = OllamaEmbeddings(model="llama3.2:3b")

    if not os.path.exists(db_path):
        store = Chroma(
            collection_name="example_collection",
            embedding_function=embeddings,
            persist_directory=db_path,  # Where to save data locally, remove if not necessary
        )
        loader = WebBaseLoader(
            web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",),
            bs_kwargs=dict(
                parse_only=bs4.SoupStrainer(
                    class_=("post-content", "post-title", "post-header")
                )
            ),
        )
        docs = loader.load()
        text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
        all_splits = text_splitter.split_documents(docs)
        # 索引文本块
        store.add_documents(documents=all_splits)
    else:
        store = Chroma(
            collection_name="example_collection",
            embedding_function=embeddings,
            persist_directory=db_path,  # Where to save data locally, remove if not necessary
        )

    return store

@tool(response_format="content_and_artifact")
def retrieve(query: str):
    """Retrieve information related to a query."""
    retrieved_docs = vector_store.similarity_search(query, k=2)
    serialized = "\n\n".join(
        (f"Source: {doc.metadata}\n" f"Content: {doc.page_content}")
        for doc in retrieved_docs
    )
    return serialized, retrieved_docs

# Step 1: 把模型和工具绑定，让模型自己决定是否要调用工具，还是直接出结果
def query_or_respond(state: MessagesState):
    """Generate tool call for retrieval or respond."""
    llm_with_tools = llm.bind_tools([retrieve])
    response = llm_with_tools.invoke(state["messages"])
    # MessagesState appends messages to state instead of overwriting
    return {"messages": [response]}


# Step 2: 根据模型返回的工具调用参数，调用相关的函数
tools = ToolNode([retrieve])


# Step 3: 根据检索到的数据，拼接数据送给模型，出结果;
# 注意，跟步骤一使用的模型不是同一个，最后这一步使用的模型没有使用工具加强
def generate(state: MessagesState):
    """Generate answer."""
    # Get generated ToolMessages
    recent_tool_messages = []
    for message in reversed(state["messages"]):
        if message.type == "tool":
            recent_tool_messages.append(message)
        else:
            break
    tool_messages = recent_tool_messages[::-1]

    # Format into prompt
    docs_content = "\n\n".join(doc.content for doc in tool_messages)
    system_message_content = (
        "You are an assistant for question-answering tasks. "
        "Use the following pieces of retrieved context to answer "
        "the question. If you don't know the answer, say that you "
        "don't know. Use three sentences maximum and keep the "
        "answer concise."
        "\n\n"
        f"{docs_content}"
    )
    conversation_messages = [
        message
        for message in state["messages"]
        if message.type in ("human", "system")
        or (message.type == "ai" and not message.tool_calls)
    ]
    prompt = [SystemMessage(system_message_content)] + conversation_messages

    # Run
    response = llm.invoke(prompt)
    return {"messages": [response]}

def show_image(graph):
    png_image = graph.get_graph().draw_mermaid_png()
    with open("mermaid.png", "wb") as f:
        f.write(png_image)
    image = Image.open("mermaid.png")
    image.show()

def init_langgraph(checkpoint_memory):
    graph_builder = StateGraph(MessagesState)
    graph_builder.add_node(query_or_respond)
    graph_builder.add_node(tools)
    graph_builder.add_node(generate)

    graph_builder.set_entry_point("query_or_respond")
    graph_builder.add_conditional_edges(
        "query_or_respond",
        tools_condition,
        {END: END, "tools": "tools"},
    )
    graph_builder.add_edge("tools", "generate")
    graph_builder.add_edge("generate", END)

    return graph_builder.compile(checkpointer=checkpoint_memory)

def test_graph():
    graph = init_langgraph(memory)
    # show_image(graph)
    thread_config = {"configurable": {"thread_id": "abc123"}}

    input_message = "What is Task Decomposition?"

    for step in graph.stream(
            {"messages": [{"role": "user", "content": input_message}]},
            stream_mode="values",
            config=thread_config
    ):
        step["messages"][-1].pretty_print()

    input_message = "Can you look up some common ways of doing it?"

    for step in graph.stream(
            {"messages": [{"role": "user", "content": input_message}]},
            stream_mode="values",
            config=thread_config,
    ):
        step["messages"][-1].pretty_print()

def test_agent():
    agent_executor = create_react_agent(llm, [retrieve], checkpointer=memory)
    # show_image(agent_executor)
    config = {"configurable": {"thread_id": "def234"}}

    input_message = (
        "What is the standard method for Task Decomposition?\n\n"
        "Once you get the answer, look up common extensions of that method."
    )

    for event in agent_executor.stream(
            {"messages": [{"role": "user", "content": input_message}]},
            stream_mode="values",
            config=config,
    ):
        event["messages"][-1].pretty_print()


llm = ChatOllama(
        model="llama3.2:3b",
        temperature=0
    )

# llm = init_chat_model("gpt-4o-mini", model_provider="openai")

vector_store = init_vector_store()

# memory = MemorySaver()
conn = sqlite3.connect("data/example.sqlite.db", check_same_thread=False)
memory = SqliteSaver(conn)

if __name__ == "__main__":
    # test_graph(config, memory)
    test_agent()



